import os
import base64
import uuid
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.styles import Alignment, Font

def export(result, beijing_time):
    
    # Step 1: Validate the report data
    if result is None:
        return None

    # Step 2: Generate excel file from the report data
    filename = generate_excel(result, beijing_time)

    # Step 3: Encode the excel file to Base64
    binary_file_data = b''
    try:
        with open(filename, 'rb') as binary_file:
            binary_file_data = binary_file.read()
    except IOError as ex:
        pass

    # Base64 encode the bytes
    base64_encoded_data = base64.b64encode(binary_file_data)
    # get the Base64 encoded data using human-readable characters.
    base64_message = base64_encoded_data.decode('utf-8')
    # delete the file from server
    try:
        os.remove(filename)
    except NotImplementedError as ex:
        pass
    return base64_message


def generate_excel(result, beijing_time, path):
    
    wb = Workbook()
    ws = wb.active
    ws.title = "Kkomia_Picture"

    # Column width
    for i in range(ord('A'), ord('I')):
        ws.column_dimensions[chr(i)].width = 25.0

    # Head image
    ws.row_dimensions[1].height = 105
    img = Image("excelexporters/kkomia.png")
    ws.add_image(img, 'A1')


    # File information
    b_r_alignment = Alignment(vertical='bottom',
                              horizontal='right',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    
    ws['A3'].alignment = b_r_alignment
    ws['A3'] = 'Database:'
    ws['B3'] = 'kkomia_picture_db'
    ws['A4'].alignment = b_r_alignment
    ws['A4'] = 'Table:'
    ws['B4'] = 'tbl_picture_file'
    ws['A5'].alignment = b_r_alignment
    ws['B5'] = beijing_time

    # Title
    title_font = Font(size = 12, bold = True)
    ws['A6'].font = title_font
    ws['A6'] = 'ID'
    ws['B6'].font = title_font
    ws['B6'] = 'PICTURE_NAME'
    ws['C6'].font = title_font
    ws['C6'] = 'PICTURE_FORMAT'
    ws['D6'].font = title_font
    ws['D6'] = 'UPDATE_UTC_TIME'
    ws['E6'].font = title_font
    ws['E6'] = 'FILE_OBJECT'

    current_row_number = 7
    for i in range(0, len(result['picture'])):
        ws['A' + str(current_row_number)] = result['picture'][i]['id']
        ws['B' + str(current_row_number)] = result['picture'][i]['meter_name']
        ws['C' + str(current_row_number)] = result['picture'][i]['space_name']
        ws['D' + str(current_row_number)] = result['picture'][i]['cost_center_name']
        ws['E' + str(current_row_number)] = result['picture'][i]['energy_category_name']
        current_row_number += 1

    filename = str(uuid.uuid4()) + '.xlsx'
    wb.save(filename)
    
    return filename



